<?php

namespace App\Models;

use Dingo\Api\Exception\ResourceException;
use Illuminate\Database\Eloquent\Model;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Illuminate\Support\Facades\DB;

class TradeQueue extends Model
{
    protected $dateFormat = 'U';

    protected $fillable = [
        'user_id','amount','unmatch_amount','queue_task_done',
        'all_match_ts_at','status','type'
    ];

    public function asset()
    {
        return $this->hasOne(Asset::class,'trade_queue_id','id');
    }
    public function matchOrderDeposit()
    {
        return $this->hasMany(MatchOrder::class,'deposit_trade_queue_id','id');
    }
    public function matchOrderWithDraw()
    {
        return $this->hasMany(MatchOrder::class,'withdraw_trade_queue_id','id');
    }

    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }

    public function createNew($isManualMatch)
    {
        if($isManualMatch == true) {
            $this->save();
        }else {
            if($this->type == 'deposit') {

            }
        }
    }

    public function withdraw($type,$amount,$nowTime,$user)
    {
        // todo 必须有冻结余额方可提现
        $isQueue = $user->tradeQueues()->where('type',$type)->orderBy('created_at','desc')->where('status','done')->first();
        if($isQueue) {
            $created_at = strtotime($isQueue->created_at);

            if(bcsub($nowTime,$created_at) > 24*60*60) {

                throw new ResourceException('error',[['error_code'=>'40004','message'=>'暂无冻结余额，不可提现！']]);
            }
        }else {
            throw new ResourceException('error',[['error_code'=>'40004','message'=>'暂无冻结余额，不可提现！']]);
        }

    }
    public function deposit($type,$amount,$nowTime,$user)
    {

        $unmatch = $user->tradeQueues()->where('type',$type)->orderBy('created_at','desc')->whereIn('status',['matching','pending'])->first();

        // todo 为匹配完成禁止下单
        if($unmatch) {
            throw new ResourceException('error',[['error_code'=>'40003','message'=>'未匹配完成,禁止下单！']]);
        }

        // todo 必须是完成24小时才可以下单
        $isQueue = $user->tradeQueues()->where('type',$type)->orderBy('created_at','desc')->where('status','done')->first();//->OrderBy('created_at','desc')->first();
        if($isQueue) {
            $created_at = strtotime($isQueue->created_at);
            if(bcsub($nowTime,$created_at) <= 24*60*60) {
                throw new ResourceException('error',[['error_code'=>'40001','message'=>'24小时之内不可重复下单！']]);

            }
            // todo 要大于等于上一次的发起单
            if($amount >= $isQueue->amount) {
                throw new ResourceException('error',[['error_code'=>'40002','message'=>'本轮投资金额要大于上一轮的投资金额！']]);

            }
        }

    }


    // 匹配订单
    public function depositMatchOrders($depositTradeQueueId,$withdrawTradeQueueId)
    {
        $isUserId = TradeQueue::where('id',$withdrawTradeQueueId)->value('user_id');
        $depositTradeQueueId = TradeQueue::whereIn('id',$depositTradeQueueId)->where('type','deposit')->where('status','matching')->where('user_id','<>',$isUserId)->pluck('id');
        if(count($depositTradeQueueId) == 0) {
            return ['error_code'=>'40007','message'=>'匹配有误！'];
        }
        DB::beginTransaction();
        try {
            foreach ($depositTradeQueueId as $depositK=>$depositV) {
                $depositAmount = TradeQueue::where('id',$depositV)->first();
                $withdrawAmount = TradeQueue::where('id',$withdrawTradeQueueId)->first();

                if($withdrawAmount->unmatch_amount >= $depositAmount->unmatch_amount) {
                    echo 1;
                    $matchOrder = MatchOrder::create([
                        'deposit_trade_queue_id'=>$depositV,
                        'withdraw_trade_queue_id'=>$withdrawTradeQueueId,
                        'amount'=>$depositAmount->unmatch_amount
                    ]);
                    TradeQueue::where('id',$depositV)->decrement('unmatch_amount',$matchOrder->amount);
                }else {
                    echo 2;
                    $matchOrder = MatchOrder::create([
                        'deposit_trade_queue_id'=>$depositV,
                        'withdraw_trade_queue_id'=>$withdrawTradeQueueId,
                        'amount'=>$withdrawAmount->unmatch_amount //bcsub($withdrawAmount->unmatch_amount,$depositAmount->unmatch_amount) // todo 可能丢失
                    ]);
                    TradeQueue::where('id',$depositV)->decrement('unmatch_amount',$matchOrder->amount);
                }

                TradeQueue::where('id',$withdrawTradeQueueId)->decrement('unmatch_amount',$matchOrder->amount);

                if(TradeQueue::where('id',$depositV)->value('unmatch_amount') == 0) {
                    TradeQueue::where('id',$depositV)->update([
                        'all_match_ts_at'=>time(),
                        'status'=>'pending'
                    ]);
                }

                if(TradeQueue::where('id',$withdrawTradeQueueId)->value('unmatch_amount') == 0) {
                    TradeQueue::where('id',$withdrawTradeQueueId)->update([
                        'all_match_ts_at'=>time(),
                        'status'=>'pending'
                    ]);
                }
            }
            DB::commit();
            return ['error_code'=>'200','message'=>'手动匹配成功！'];
        }catch (\Exception $exception) {
            \Log::error('create TradeQueue orders error', ['error' => $exception->getMessage()]);
            DB::rollback();
            throw new ResourceException('error',[['error_code'=>'40006','message'=>'手动匹配未成功！']]);

        }

    }

    public function withdrawMatchOrders($depositTradeQueueId,$withdrawTradeQueueId)
    {
        $isUserId = TradeQueue::where('id',$depositTradeQueueId)->value('user_id');

        $withdrawTradeQueueId = TradeQueue::whereIn('id',$withdrawTradeQueueId)->where('type','withdraw')->where('status','matching')->where('user_id','<>',$isUserId)->pluck('id');

        if(count($withdrawTradeQueueId) == 0) {
            return ['error_code'=>'40007','message'=>'匹配有误！'];
        }
        DB::beginTransaction();
        try {
            foreach ($withdrawTradeQueueId as $withdrawK=>$withdrawV) {
                $withdrawAmount = TradeQueue::where('id',$withdrawV)->first();
                $depositAmount = TradeQueue::where('id',$depositTradeQueueId)->first();

                if($depositAmount->unmatch_amount >= $withdrawAmount->unmatch_amount) {
                    echo 1;
                    $matchOrder = MatchOrder::create([
                        'deposit_trade_queue_id'=>$depositTradeQueueId,
                        'withdraw_trade_queue_id'=>$withdrawV,
                        'amount'=>$withdrawAmount->unmatch_amount
                    ]);

                    TradeQueue::where('id',$withdrawV)->decrement('unmatch_amount',$matchOrder->amount);
                }else {
                    echo 2;
                    $matchOrder = MatchOrder::create([
                        'deposit_trade_queue_id'=>$depositTradeQueueId,
                        'withdraw_trade_queue_id'=>$withdrawV,
                        'amount'=>$depositAmount->unmatch_amount //bcsub($withdrawAmount->unmatch_amount,$depositAmount->unmatch_amount) // todo 可能丢失
                    ]);

                    TradeQueue::where('id',$withdrawV)->decrement('unmatch_amount',$matchOrder->amount);

                }
                TradeQueue::where('id',$depositTradeQueueId)->decrement('unmatch_amount',$matchOrder->amount);

                if(TradeQueue::where('id',$withdrawV)->value('unmatch_amount') == 0) {
                    TradeQueue::where('id',$withdrawV)->update([
                        'all_match_ts_at'=>time(),
                        'status'=>'pending'
                    ]);
                }
                // 判断
                if(TradeQueue::where('id',$depositTradeQueueId)->value('unmatch_amount') == 0) {
                    TradeQueue::where('id',$depositTradeQueueId)->update([
                        'all_match_ts_at'=>time(),
                        'status'=>'pending'
                    ]);
                }
            }
            //
            DB::commit();
            return ['error_code'=>'200','message'=>'手动匹配成功！'];

        }catch (\Exception $exception) {
            \Log::error('create TradeQueue orders error', ['error' => $exception->getMessage()]);
            DB::rollback();
            throw new ResourceException('error',[['error_code'=>'40006','message'=>'手动匹配未成功！']]);

        }
    }
}
